<template>
  <div class="app-container">
    <el-card class="filter-container">
      <div>
        <i class="el-icon-search" />
        <span>筛选搜索</span>
        <div class="filter-btn">
          <el-button
            icon="el-icon-search"
            type="primary"
            size="small"
            @click="handleSearchList()"
          >
            查询
          </el-button>
          <el-button
            icon="el-icon-setting"
            size="small"
            @click="handleResetSearch()"
          >
            重置
          </el-button>

          <el-button
            class="btn-add"
            type="success"
            size="mini"
            icon="el-icon-plus"
            @click="add"
          >
            添加
          </el-button>
        </div>

      </div>
      <div style="margin-top: 25px">
        <el-form :inline="true" :model="listQuery" size="small">
          <el-row>
            <el-col :sm="12" :lg="6">
              <el-form-item label="名称：">
                <el-input v-model="listQuery.name" placeholder="名称" />
              </el-form-item>
            </el-col>

            <el-col :sm="12" :lg="6">
              <el-form-item label="状态：">
                <el-select v-model="listQuery.status" placeholder="全部" clearable>
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>

        </el-form>
      </div>
    </el-card>

    <el-card class="table-container">
      <el-table
        v-loading="listLoading"
        element-loading-text="加载中"
        :data="list"
        border
        fit
        style="width: 100%"
        class="table-list"
      >
        <el-table-column align="center" width="200" label="名称">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusTypeFilter">{{ scope.row.status | statusTextFilter }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="备注">
          <template slot-scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="operate-cell">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="allocRole(scope.row)"
            >分配角色
            </el-button>

            <el-divider direction="vertical" />

            <el-button
              size="mini"
              type="success"
              @click="update(scope.row)"
            >编辑
            </el-button>

            <el-divider direction="vertical" />

            <el-button
              v-if="scope.row.status === 0"
              size="mini"
              @click="enabled(scope.row)"
            >启用
            </el-button>
            <el-button
              v-else
              size="mini"
              type="warning"
              @click="disable(scope.row)"
            >禁用
            </el-button>

            <el-divider direction="vertical" />

            <el-button
              size="mini"
              type="danger"
              @click="remove(scope.row)"
            >删除
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageLimit" @pagination="getList" />
    </el-card>

    <el-dialog
      :title="isAdd ? '新增用户组' : '编辑用户组'"
      :visible.sync="editOperFormVisible"
      center
      width="30%"
    >
      <el-form
        ref="editOperForm"
        :rules="editOperFormRules"
        :model="editOperForm"
      >
        <el-form-item label="名称：" prop="name">
          <el-input
            v-model="editOperForm.name"
            placeholder="名称"
          />
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            v-model="editOperForm.remark"
            placeholder="备注"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editOperFormVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="handleSaveUserGroup">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="分配角色"
      :visible.sync="updateRoleVisible"
      width="30%"
    >
      <el-select
        v-model="roleIds"
        multiple
        filterable
        size="small"
        reserve-keyword
        placeholder="请输入角色名"
        style="width: 80%"
      >
        <el-option
          v-for="item in roleList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="updateRoleVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" size="small" @click="handleUpdateRoleconfirm()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

import {
  getPageList,
  create,
  updateById,
  removeById,
  updateStatus,
  updateRoles
} from '@/api/system/user-group'

import {
  getListByUserGroup,
  getList as getRoleList
} from '@/api/system/role'

import Pagination from '@/components/Pagination'

const defaultListQuery = {
  pageNum: 1,
  pageLimit: 10,
  sorts: '-createTime'
}

const statusMap = {
  1: {
    type: 'success',
    text: '启用'
  },
  0: {
    type: 'warning',
    text: '禁用'
  }
}

export default {
  name: 'UserGroupList',
  components: { Pagination },
  filters: {
    statusTypeFilter(status) {
      return statusMap[status].type
    },
    statusTextFilter(status) {
      return statusMap[status].text
    }
  },
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery),
      list: [],
      total: 0,

      statusOptions: [{
        value: 1,
        label: '启用'
      }, {
        value: 0,
        label: '禁用'
      }],

      listLoading: true,
      loading: false,

      isAdd: false,
      editOperFormVisible: false,
      editOperForm: {},
      editOperFormRules: {
        name: [{ required: true, trigger: 'blur', message: '请填写账号' }]
      },

      roleListInit: false,
      updateRoleVisible: false,
      roleList: [],
      // 用户具有的角色id
      roleIds: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getPageList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleSearchList() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery)
    },
    enabled(row) {
      this.$confirm('是否要启用账户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateStatus(row.id, 1)
      })
    },
    dsiabled(row) {
      this.$confirm('是否要禁用账户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateStatus(row.id, 0)
      })
    },
    updateStatus(ids, status) {
      updateStatus({
        ids,
        status
      }).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        })
      })
    },
    add() {
      this.isAdd = true
      this.editOperForm = {}
      this.editOperFormVisible = true
    },
    handleSaveUserGroup() {
      this.$refs.editOperForm.validate(valid => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const params = Object.assign({}, this.editOperForm)

            if (this.isAdd) {
              create(params).then(_ => {
                this.$message.success('新建用户组成功，如需登录请分配合适的角色！')
                this.editOperFormVisible = false
                this.getList()
              })
            } else {
              updateById(params.id, params).then(_ => {
                this.$message.success('修改用户组成功！')
                this.editOperFormVisible = false
                this.getList()
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    update(row) {
      this.isAdd = false
      this.editOperForm = Object.assign({}, row)
      this.editOperFormVisible = true
    },
    remove(row) {
      this.$confirm('是否要删除用户组?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeById(row.id).then(_ => {
          this.getList()
        })
      })
    },
    allocRole(row) {
      this.currentUserGroupId = row.id

      if (!this.roleListInit) {
        this.getRoleList()
      }

      // 清空当前角色
      this.roleIds = []
      this.getListByUserGroup(this.currentUserGroupId)
      this.updateRoleVisible = true
    },
    getRoleList() {
      getRoleList({
        status: 1
      }).then(res => {
        this.roleList = res.data
      })
    },
    getListByUserGroup(userGroupId) {
      getListByUserGroup(userGroupId).then(res => {
        const roleIds = []
        res.data.map(item => {
          roleIds.push(item.id)
        })

        this.roleIds = roleIds
      })
    },
    handleUpdateRoleconfirm() {
      this.$confirm('确认分配用户组?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateRoles(this.currentUserGroupId, this.roleIds).then(_ => {
          this.$message.success('分配用户组成功！')
          this.updateRoleVisible = false
          this.getList()
        })
      })
    }

  }
}
</script>

<style scoped>

</style>
